/**
 * @(#) WorkMediator.as
 *
 * @date		2009. 02. 25.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	근무 - Mediator
 * 				근무관리 Presentation Logic을 관리 
 */
package com.skt.common_hr.teamworktime_sac.view
{
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.calendar.DailyItem;
	import com.skt.common_hr.common.calendar.Holiday;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.OverViewMediator;
	import com.skt.common_hr.teamworktime_sac.TeamWorkTimeFacade;
	import com.skt.common_hr.teamworktime_sac.events.SelOrgEvent;
	import com.skt.common_hr.teamworktime_sac.events.TeamWorkTimeEvent;
	import com.skt.common_hr.teamworktime_sac.events.WorkTimeEvent;
	import com.skt.common_hr.teamworktime_sac.model.CalendarProxy;
	import com.skt.common_hr.teamworktime_sac.model.HolidayProxy;
	import com.skt.common_hr.teamworktime_sac.model.MemberSearchProxy;
	import com.skt.common_hr.teamworktime_sac.model.OrgProxy;
	import com.skt.common_hr.teamworktime_sac.model.TeamWorkListProxy;
	import com.skt.common_hr.teamworktime_sac.model.VacationCodeProxy;
	import com.skt.common_hr.teamworktime_sac.model.vo.DateVO;
	import com.skt.common_hr.teamworktime_sac.model.vo.MemberVO;
	import com.skt.common_hr.teamworktime_sac.model.vo.ReqVacationListVO;
	import com.skt.common_hr.teamworktime_sac.model.vo.TeamWorkListVO;
	import com.skt.common_hr.teamworktime_sac.model.vo.VacationVO;
	import com.skt.common_hr.teamworktime_sac.view.components.TeamWorkTimeOverView;
	import com.wcl.utils.DateUtil;
	
	import mx.collections.ArrayCollection;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	

	public class TeamWorkTimeMediator extends OverViewMediator
	{
		public static const NAME:String = "TeamWorkTimeMediator"; 
		
		
		private var teamWorkList:ArrayCollection;
		private var selectedDept:String;
		
		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function TeamWorkTimeMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		override protected function initializeView():void
 		{
 			preloadData();
 			checkAuthority(Variables.authorities);
 			super.initializeView();
 		}
 		
 		override protected function activatedView():void
 		{
 			setEventListeners();
 			loadTeamMember(Variables.myOrgCode);
 			view.currentCalendarDate = DateUtil.todayNoTime();
 			
 			selectedDept = Variables.myOrgCode;
 			view.txtOrg.data = selectedDept;
 			view.txtOrg.text = Variables.myOrg;
 		}
 		
 		override protected function closedView():void
 		{
 			removeEventListeners();
 		}
 		
 		private function setEventListeners():void
 		{
 			view.addEventListener(WorkTimeEvent.CHANGED_WEEK, onChangedWeek);		// Calendar에서 월이 변경되어 있을때
 			view.addEventListener(SelOrgEvent.SELECTED_ORG, onSelectedOrg);
 			view.addEventListener(TeamWorkTimeEvent.CLICK_WORKTIME_ITEM, onClickWorkTimeItem);
 		}
 		
 		private function removeEventListeners():void
 		{
 			view.removeEventListener(WorkTimeEvent.CHANGED_MONTH, onChangedWeek);		// Calendar에서 월이 변경되어 있을때
 			view.removeEventListener(SelOrgEvent.SELECTED_ORG, onSelectedOrg);
 			view.removeEventListener(TeamWorkTimeEvent.CLICK_WORKTIME_ITEM, onClickWorkTimeItem);
 		}
 		
		private function preloadData():void
 		{
 			var orgProxy:OrgProxy = facade.retrieveProxy(OrgProxy.NAME) as OrgProxy;
 			orgProxy.load(Variables.myPernr, "X");
 			
			// 휴가 종류 코드를 로드한다.
  			var codeProxy:VacationCodeProxy = facade.retrieveProxy(VacationCodeProxy.NAME) as VacationCodeProxy;
 			codeProxy.load(Variables.myPernr);
 		}
 		
 		
 		private function checkAuthority(authList:ArrayCollection):void
 		{
 			for each(var vo:* in authList)
 			{
 				if(vo.EMENU == "ALTERREQWORK") {
 					view.registable = true;
 					return;
 				}
 			}
 			view.registable = false;
 		}
 		
 		private function loadTeamMember(code:String):void
 		{
 			var proxy:MemberSearchProxy = facade.retrieveProxy(MemberSearchProxy.NAME) as MemberSearchProxy;
 			proxy.load(code, "");
 		}
 		
 		private function loadCalendarData(pernr:String, month:Date):void
 		{
 			var targetMonth:String = DateUtil.toYYYYMMString(month);
 			var dateProxy:CalendarProxy = facade.retrieveProxy(CalendarProxy.NAME) as CalendarProxy;
 			dateProxy.load(pernr, targetMonth);
 		}
		
		private function loadHolidayData(s:Date, e:Date):void
		{
			var proxy:HolidayProxy = facade.retrieveProxy(HolidayProxy.NAME) as HolidayProxy;
			proxy.load(s, e);
		}
		
		private function loadWeeklyData(orgCode:String, s:Date, e:Date):void
		{
			clearWorkTimeList();
			var proxy:TeamWorkListProxy = facade.retrieveProxy(TeamWorkListProxy.NAME) as TeamWorkListProxy;
			proxy.load(orgCode, s, e);
		}
		
 		private function onSelectedOrg(event:SelOrgEvent):void
 		{
 			selectedDept = event.orgCode;
			loadTeamMember(selectedDept); 			
 		}
 		
  		private function onChangedWeek(event:WorkTimeEvent):void
 		{
  			//currentMonth = new Date(event.beginDate);
  			
 			//loadCalendarData((selectedMember!=null) ? selectedMember.PERNR:null, currentMonth);
 			loadHolidayData(DateUtil.startOfWeek(event.beginDate), DateUtil.endOfWeek(event.beginDate));
 			loadWeeklyData(selectedDept, DateUtil.startOfWeek(event.beginDate), DateUtil.endOfWeek(event.beginDate));
 		}
 		
 		private function onClickWorkTimeItem(e:TeamWorkTimeEvent):void
 		{
 			CommonAlert.showMessage("", "선택: " + e.key);
 		}
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return basicInterestMessages.concat( [
					TeamWorkTimeFacade.LOAD_NAMESEARCH_COMPLETE,
					TeamWorkTimeFacade.LOAD_NAMESEARCH_FAILED,
					TeamWorkTimeFacade.LOAD_CALENDAR_COMPLETE,
					TeamWorkTimeFacade.LOAD_CALENDAR_FAILED,
					HolidayProxy.LOAD_HOLIDAYS_COMPLETE,
					HolidayProxy.LOAD_HOLIDAYS_FAILED,
					TeamWorkTimeFacade.LOAD_ORGLIST_COMPLETE,
					TeamWorkTimeFacade.LOAD_ORGLIST_FAILED,
					TeamWorkTimeFacade.INSERT_REQ_VACATION_COMPLETE,
					TeamWorkTimeFacade.INSERT_REQ_WORKTIME_COMPLETE,
					TeamWorkListProxy.LOAD_TEAMWORKLIST_COMPLETE,
					TeamWorkListProxy.LOAD_TEAMWORKLIST_FAILED,
					DeleteWorkTimeMediator.DELETED_WORKTIME
					]);
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			super.handleNotification(note);
			switch(note.getName()) 
			{
				case TeamWorkTimeFacade.LOAD_NAMESEARCH_COMPLETE:
					//view.memberList = (note.getBody() as MemberSearchProxy).memberList;
					view.teamWorkList = initTeamWorkTimeList(note.getBody() as MemberSearchProxy);
					commonFacade.setStatusMessage("STATUS_SELECT_MEMBER"); 
					break;
				case TeamWorkTimeFacade.LOAD_CALENDAR_COMPLETE:
					//view.btnInput.enabled = true;
					//setCalendar(note.getBody() as CalendarProxy);
					break;
				case TeamWorkTimeFacade.LOAD_CALENDAR_FAILED:
					break;
				case HolidayProxy.LOAD_HOLIDAYS_COMPLETE:
					view.setHolidays((note.getBody() as HolidayProxy).list);
					break;
				case TeamWorkTimeFacade.LOAD_ORGLIST_COMPLETE:
					view.orgList = (note.getBody() as OrgProxy).orgList;
					break;
				case TeamWorkTimeFacade.LOAD_ORGLIST_FAILED:
					break;
				case TeamWorkListProxy.LOAD_TEAMWORKLIST_COMPLETE:
					setTeamWorkTimeList(note.getBody() as TeamWorkListProxy);
					view.teamWorkList.refresh();
					break;
				case TeamWorkListProxy.LOAD_TEAMWORKLIST_FAILED:
					break;
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}
		
		
		

		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Event handler (from View, Internal or....)
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		
		private function initTeamWorkTimeList(proxy:MemberSearchProxy):ArrayCollection
		{
			var list:ArrayCollection = new ArrayCollection();
			for each(var src:MemberVO in proxy.memberList) {
				var vo:TeamWorkListVO = new TeamWorkListVO();
				vo.PERNR = src.PERNR;
				vo.ENAME = src.ENAME;
				list.addItem(vo);
			}
			return list;				
		}
		
		private function clearWorkTimeList():void
		{
			for each(var vo:TeamWorkListVO in view.teamWorkList) {
				vo.AWART0 = "";
				vo.AWATX0 = "";
				vo.AWART1 = "";
				vo.AWATX1 = "";
				vo.AWART2 = "";
				vo.AWATX2 = "";
				vo.AWART3 = "";
				vo.AWATX3 = "";
				vo.AWART4 = "";
				vo.AWATX4 = "";
				vo.AWART5 = "";
				vo.AWATX5 = "";
				vo.AWART6 = "";
				vo.AWATX6 = "";
				vo.content0 = null;
				vo.content1 = null;
				vo.content2 = null;
				vo.content3 = null;
				vo.content4 = null;
				vo.content5 = null;
				vo.content6 = null;
			}
		}
		
		private function setTeamWorkTimeList(proxy:TeamWorkListProxy):void
		{
			//view.teamWorkList
			for each(var src:ReqVacationListVO in proxy.workTimeList) {
				for each(var vo:TeamWorkListVO in view.teamWorkList) {
					if(vo.PERNR==src.PERNR) 
						setWorkTimeRecord(vo, src);
				}
			}
		}
		
		private function setWorkTimeRecord(target:TeamWorkListVO, src:ReqVacationListVO):void
		{
			var iDate:Date = new Date(src.BEGDA);
			for(;Number(iDate)<=Number(src.ENDDA); iDate.date++) {
				var dayIndex:int = DateUtil.daySpan(view.startOfWeek, iDate)-1;
				if(dayIndex>=0 && dayIndex<=6) {
					target["AWART"+dayIndex] = src.AWART; 
					target["AWATX"+dayIndex] = src.AWATX; 
					target["content"+dayIndex] = src;
				}
			}
			//target.AWART0 = src.AWART;
			//target.AWATX0 = src.AWATX;
		}
		
		


		private function toCalendarHoliday(src:ArrayCollection):ArrayCollection
		{
			var coll:ArrayCollection = new ArrayCollection();
			for each(var rec:DateVO in src) {
				var vo:Holiday = new Holiday();
				vo.DATUM = new Date(rec.DATUM);
				vo.DTYPE = rec.DTYPE;
				vo.DTEXT = rec.DTEXT;
				coll.addItem(vo);
			}
			return coll;
		}
		
		private var buttonStyleList:Array = ["btn02Return04", "btn02barYellow", "btn02barBlue", "btn02barPink", "btn02barGreen", ""];
		private function toCalendarItems(src:ArrayCollection):ArrayCollection
		{
			var coll:ArrayCollection = new ArrayCollection();
			for each(var rec:VacationVO in src) {
				var vo:DailyItem = new DailyItem();
				vo.WGBN				= rec.WGBN;
				vo.WGBNT			= rec.WGBNT;
				vo.DGBN				= rec.DGBN;
				vo.DGBNT			= rec.DGBNT;
				vo.AWART			= rec.AWART;
				vo.AWATX			= rec.AWATX;
				vo.BEGDA			= new Date(rec.BEGDA);
				vo.ENDDA			= new Date(rec.ENDDA);
				vo.BEGUZ			= new Date(rec.BEGUZ);
				vo.ENDUZ			= new Date(rec.ENDUZ);
				vo.WSTATUS			= rec.WSTATUS;
				vo.WSTATX			= rec.WSTATX;
				vo.TABNR			= rec.TABNR;
				vo.GUBUN			= rec.GUBUN;
				vo.TEXT1			= rec.TEXT1;
				vo.GWAREKEY			= rec.GWAREKEY;
				vo.label = vo.AWATX;
				vo.tootip = vo.TEXT1;
				vo.style = (vo.WSTATUS=="4") ? buttonStyleList[0] : buttonStyleList[parseInt(vo.DGBN)];
					if(vo.WSTATUS!="3") {	
						vo.clickable = false;
						vo.GWAREKEY = "";
					}
					else {
						/*
						if((vo.DGBN=="2" || vo.DGBN=="1") && deletableDay(vo.BEGDA)) {
							vo.clickable = true;
							vo.tootip = "클릭하시면 삭제할 수 있습니다.";
						}
						else {
							vo.clickable = false;
							vo.GWAREKEY = "";
						}
						*/
						vo.clickable = false;
						vo.GWAREKEY = "";
					}
				coll.addItem(vo);
			}
			return coll;
		}
		
		private function deletableDay(date:Date):Boolean
		{
			var today:Date = DateUtil.todayNoTime();
			today.date = 1;
			today.date--;
			today.date = 1;
			return (date > today) ? true : false; 
		}
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():TeamWorkTimeOverView
        {
            return viewComponent as TeamWorkTimeOverView;
        }
	}
}